# lingxin-api/routers/control.py
from fastapi import APIRouter, Query
from smartpi import motor, ultrasonic, base_driver, led

router = APIRouter(prefix="/ctrl", tags=["控制与传感"])

# -------------- 移动接口 --------------
@router.post("/move_angle")
def move_angle(
    speed: int = Query(50, ge=-100, le=100),
    angle: int = Query(360, ge=0, le=65535, description="编码器角度")
):
    """左右轮同时转指定角度"""
    motor.set_motor_angle(1, speed, angle)   # 左
    motor.set_motor_angle(2, speed, angle)   # 右
    return {"speed": speed, "angle": angle}

# -------------- 传感器接口 --------------
@router.get("/distance")
def distance(port: str = Query("P1", regex="^P[1-6]$")):
    """超声波测距（cm）"""
    port_num = int(port[1])      # 提取 "P1" → 1
    dist = ultrasonic.get_value(port_num)
    return {"port": port, "distance_cm": dist}

@router.get("/battery")
def battery():
    """电池电量信息"""
    bat = base_driver.read_battery()
    return {"battery": bat.decode() if isinstance(bat, bytes) else bat}

# -------------- 彩灯接口 --------------
@router.post("/led")
def set_led(
    port: int = Query(..., ge=1, le=6, description="P端口 1-6"),
    color: int = Query(..., ge=0, le=7, description="0关 1红 2绿 3蓝 4黄 5紫 6青 7白")
):
    """设置彩灯颜色"""
    led.set_color(port, color)
    return {"port": f"P{port}", "color": color}

